package com.whj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whj.domain.constants.SystemConstants;
import com.whj.domain.dto.CategoryDTO;
import com.whj.domain.entity.Article;
import com.whj.domain.entity.Category;
import com.whj.domain.entity.Link;
import com.whj.domain.entity.User;
import com.whj.domain.enums.AppHttpCodeEnum;
import com.whj.domain.response.ResponseResult;
import com.whj.domain.vo.CategoryVO;
import com.whj.domain.vo.PageVo;
import com.whj.exception.SystemException;
import com.whj.mapper.CategoryMapper;
import com.whj.service.ArticleService;
import com.whj.service.CategoryService;
import com.whj.utils.BeanCopyUtils;
import com.whj.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 分类表(Category)表服务实现类
 *
 * @author wanghaijun
 * @since 2023-05-23 08:54:21
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {


    @Autowired
    private ArticleService articleService;

    /**
     * 页面上需要展示分类列表，用户可以点击具体的分类查看该分类下的文章列表。
     * 注意： ①要求只展示有发布正式文章的分类 ②必须是正常状态的分类
     *
     * @return 分类标签list
     */
    @Override
    public ResponseResult<CategoryVO> getCategoryList() {

        // 查询文章表 状态为已发布的文章
        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Article::getStatus, SystemConstants.ARTICLE_STATUS_NORMAL);
        List<Article> articleList = articleService.list(queryWrapper);
        //获取文章分类的id，并用set去重
        Set<Long> categoryId = articleList.stream().map(
                        Article::getCategoryId)
                .collect(Collectors.toSet());
        // 查询分类表
        List<Category> categories = listByIds(categoryId);
        categories = categories.stream()
                .filter(category -> SystemConstants.STATUS_NORMAL.equals(category.getStatus()))
                .collect(Collectors.toList());

        List<CategoryVO> categoryVOS = BeanCopyUtils.copyBeanList(categories, CategoryVO.class);
        return ResponseResult.okResult(categoryVOS);
    }


    /**
     * 查询所有分类的方法
     *
     * @return
     */
    @Override
    public List<CategoryVO> listAllCategory() {
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getStatus, SystemConstants.NORMAL);
        List<Category> list = list(wrapper);
        List<CategoryVO> categoryVos = BeanCopyUtils.copyBeanList(list, CategoryVO.class);
        return categoryVos;
    }

    /**
     * 查询分类并分页
     *
     * @param pageNum
     * @param pageSize
     * @param name
     * @param status
     * @return
     */
    @Override
    public ResponseResult selectCategoryByPage(Integer pageNum, Integer pageSize, String name, String status) {
        Long userId = SecurityUtils.getUserId();
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Category::getCreateBy, userId);
        wrapper.like(StringUtils.hasText(name), Category::getName, name);
        wrapper.eq(StringUtils.hasText(status), Category::getStatus, status);

        Page<Category> page = new Page<>(pageNum, pageSize);
        page(page, wrapper);
        return ResponseResult.okResult(new PageVo(page.getRecords(), page.getTotal()));
    }

    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 新增分类
     *
     * @param categoryVO
     * @return
     */
    @Transactional
    @Override
    public ResponseResult addCategory(CategoryVO categoryVO) {

        // 判断名称是否存在
        String name = categoryVO.getName();
        if (categoryNameExist(name, categoryVO.getId())) {
            throw new SystemException(AppHttpCodeEnum.NAME_IS_EXISTS);
        }
        Category category = BeanCopyUtils.copyBean(categoryVO, Category.class);
        categoryMapper.insert(category);
        return ResponseResult.okResult();
    }

    /**
     * 通过id搜索分类
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult selecCategoryById(Long id) {
        Category category = categoryMapper.selectById(id);
        return ResponseResult.okResult(category);
    }

    /**
     * 更新分类
     *
     * @param categoryDTO
     * @return
     */
    @Transactional
    @Override
    public ResponseResult updateCategory(CategoryDTO categoryDTO) {
        if (categoryNameExist(categoryDTO.getName(), categoryDTO.getId())) {
            throw new SystemException(AppHttpCodeEnum.NAME_IS_EXISTS);
        }
        Category category = BeanCopyUtils.copyBean(categoryDTO, Category.class);
        categoryMapper.updateById(category);
        return ResponseResult.okResult();
    }

    /**
     * 删除分类
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteCategory(List<String> id) {
        List<Long> collect = id.stream().map(s -> Long.parseLong(s.trim())).collect(Collectors.toList());
        categoryMapper.deleteBatchIds(collect);
        return ResponseResult.okResult();
    }

    private boolean categoryNameExist(String userName, Long id) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Category::getName, userName);
        Category category = categoryMapper.selectOne(queryWrapper);

        if (!StringUtils.isEmpty(category)) {
            Long idDB = category.getId();
            if (!idDB.equals(id)) {
                return true;
            }
        }
        return false;
    }

}
